//
//  ServerEngine.m
//  fugitive
//
//  Created by Eugene Bistolas on 5/26/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ServerEngine.h"


@implementation ServerEngine
@synthesize playerType;
@synthesize playerID; 
@synthesize playerName = playerName_; 
@synthesize players = players_; 
@synthesize powerups = powerups_; 
@synthesize startTarget = startTarget_; 
@synthesize endTarget = endTarget_; 
@synthesize gameRunning; 
@synthesize endTime = endTime_; 
@synthesize alertStatus; 
@synthesize gameInstance; 

-(id) initWithPlayerID:(int) pid playerType:(int) ptype playerName:(NSString*) pname gameInstance:(int)g {
   self = [self init]; 
   if (self) {
      decoder = [JSONDecoder decoder]; 
      self.playerID = pid;
      self.playerType = ptype; 
      self.playerName = pname; 
      self.gameInstance = g; 
      players_ = [[NSMutableArray alloc] init]; 
      powerups_ = [[NSMutableArray alloc] init]; 
   }
   return self; 
}

- (id) init {
   self = [super init]; 
   if (self) {
      decoder = [JSONDecoder decoder]; 
      players_ = [[NSMutableArray alloc] init]; 
      powerups_ = [[NSMutableArray alloc] init]; 
   }
   return self; 
}


//Use this during initial loading only, call once only otherwise you WILL have duplicate table entires for this user. 
//This is just for getting the player registered intiially and passing back the players pid for use during the entirety of the game. 
+ (int) registerNewPlayerWithName: (NSString*) name type:(int) t gameInst:(int)g {
   int newPID = 0;
   
   //ensure us a nonzero pid
   while (newPID == 0) {
      newPID = [Player generatePlayerID]; 
   }
   NSString *urlStr = [NSString stringWithFormat:@"http://remote.bistolas.info:8888/insert.php?table=MAIN&ID=%d&UserName=%@&PlayerType=%d&Lat=%f&Lng=%f&gameInst=%d", newPID, name, t, 0, 0, g]; 
   NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
   NSLog(@"URL: %@\n", url); 
   NSLog(@"URLStr: %@\n", urlStr); 
   NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
   NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil]; 
   NSString *status = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
   //Recursive system call here. This should be interesting. 
   
   NSLog(@"Register Status: %@", status); 
   if ([status compare:@"0"] != NSOrderedSame) {
      NSLog(@"Error: PlayerID already exists. Regenerating"); 
      [self registerNewPlayerWithName:name type:t gameInst:g]; 
   }
   
   return newPID; 
}


+ (void) registerGameInformationWithInstance:(int) gIst endTime:(int) endTime startLocation:(CLLocationCoordinate2D) start stopLocation:(CLLocationCoordinate2D) stop {
   
   NSString *urlStr = [NSString stringWithFormat:@"http://remote.bistolas.info:8888/insert.php?table=GameData&ID=%d&endtime=%d&startlat=%f&startlng=%f&stoplat=%f&stoplng=%f&status=1", gIst, endTime, start.latitude, start.longitude, stop.latitude, stop.longitude]; 
   NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
   NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
   [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil]; 
}

+ (void) registerNewPowerupWithGameInstance:(int) ginst name:(NSString*)n type:(int) t location: (CLLocationCoordinate2D) coord {
   NSString *urlStr = [NSString stringWithFormat:@"http://remote.bistolas.info:8888/insert.php?table=POWERUPS&ID=%d&gameInst=%d&type=%d&name=%s&lat=%f&lng=&f", [Powerup generatePowerupID], ginst, t, n, coord.latitude, coord.longitude];
   NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
   NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
   [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil]; 
}

//Gets initial game setup data. 
- (void) getInitialGameData {
   //Get game data here. 
   NSURL *url = [NSURL URLWithString:@"http://remote.bistolas.info:8888/json_getGameData.php"];
   NSMutableURLRequest *gameReq = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
   NSData *gameData  = [NSURLConnection sendSynchronousRequest:gameReq returningResponse:nil error:nil]; 
   NSDictionary *gameDict = [decoder objectWithData:gameData error:nil]; 
   
   
   //Decode game data
   for (id key in gameDict) {
      if ([[key objectForKey:@"ID"] intValue] == self.gameInstance) {
         //Set game running status
         self.gameRunning = [[key objectForKey:@"status"] intValue]; 
         
         
         //Set start/stop endpoints. 
         CLLocationCoordinate2D tmpCoord = CLLocationCoordinate2DMake([[key objectForKey:@"startlat"] doubleValue],
                                                                      [[key objectForKey:@"startlng"] doubleValue]); 
         Targets *starg = [[Targets alloc] initWithCoordinate:tmpCoord
                                                         type:STARTTARGET]; 
         self.startTarget = starg; 
         [starg release]; 
         
         tmpCoord = CLLocationCoordinate2DMake([[key objectForKey:@"stoplat"] doubleValue],
                                               [[key objectForKey:@"stoplng"] doubleValue]); 
         Targets *sttarg = [[Targets alloc] initWithCoordinate:tmpCoord type:STOPTARGET]; 
         self.endTarget = sttarg; 
         [sttarg release]; 
         
         //End date is stored as seconds from epoch in nsdate class. 
         self.endTime = [[key objectForKey:@"endtime"] intValue]; 
      }     
   }
}

//Gets current player data as well as powerup data. 
- (void) getGameData {
   NSURL *url; 
   
   //Get player data here. 
   url = [NSURL URLWithString:@"http://remote.bistolas.info:8888/json_getPlayerData.php"]; 
   NSMutableURLRequest *playerReq = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
   NSData *playerData = [NSURLConnection sendSynchronousRequest:playerReq returningResponse:nil error:nil]; 
   NSDictionary *playerDict = [decoder objectWithData:playerData error:nil]; 
   
   //Get powerup data here
   url = [NSURL URLWithString:@"http://remote.bistolas.info:8888/json_getPowerupData.php"]; 
   NSMutableURLRequest *powerupReq = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
   NSData *powerupData = [NSURLConnection sendSynchronousRequest:powerupReq returningResponse:nil error:nil]; 
   NSDictionary *powerupDict = [decoder objectWithData:powerupData error:nil];
   
   //Decode player data
   for (id key in playerDict) {
      if (self.gameInstance == [[key objectForKey:@"gameInst"] intValue]) {
         CLLocationCoordinate2D tmpcoord = CLLocationCoordinate2DMake([[key objectForKey:@"Lat"] doubleValue], 
                                                                      [[key objectForKey:@"Lng"] doubleValue]);
         Player *p = [[Player alloc] initWithPlayerID:[[key objectForKey:@"ID"] intValue] name:[key objectForKey:@"UserName"] type:[[key objectForKey:@"PlayerType"] intValue] coordinate:tmpcoord]; 
         [self.players addObject:p]; 
      }
   }
   
   //Decode powerup data
   for (id key in powerupDict) {
      if (self.gameInstance == [[key objectForKey:@"gameInst"] intValue]) {
         CLLocationCoordinate2D tmpcoord = CLLocationCoordinate2DMake([[key objectForKey:@"lat"] doubleValue], [[key objectForKey:@"lng"] doubleValue]); 
         Powerup *p = [[Powerup alloc] initWithPowerupID:[[key objectForKey:@"ID"] intValue] type:[[key objectForKey:@"type"] intValue] coordinate:tmpcoord]; 
         [self.powerups addObject:p]; 
      }
   }
}

//Ensure lat/lng/alertStatus is pushed to engine before 
- (void) updatePlayerLocation:(CLLocationCoordinate2D) coord {
   NSURL *url; 
   //Remove player from table. 
   
   NSString *urlStr = [NSString stringWithFormat:@"http://remote.bistolas.info:8888/query.php?query=delete from MAIN where ID=%d", self.playerID];
   NSLog(@"URL: %@\n", urlStr); 
   url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
   
   NSMutableURLRequest *delReq = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
   NSData *delData = [NSURLConnection sendSynchronousRequest:delReq returningResponse:nil error:nil]; 
   NSString *status = [[NSString alloc] initWithData:delData encoding:NSUTF8StringEncoding]; 
   NSLog(@"Status: %@\n", status); 
   
   //Reinsert with updated information. 
   urlStr = [NSString stringWithFormat:@"http://remote.bistolas.info:8888/insert.php?table=MAIN&ID=%d&UserName=%@&PlayerType=%d&Lat=%f&Lng=%f&Alert%d&gameInst=%d", self.playerID, self.playerName, self.playerType, coord.latitude, coord.longitude, self.alertStatus, self.gameInstance];
   url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
   NSMutableURLRequest *addReq = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
   [NSURLConnection sendSynchronousRequest:addReq returningResponse:nil error:nil]; 
}

- (void) clearAllServerData {
   NSURL *url;
   NSMutableURLRequest *delReq; 
   //Clear main table. ID 0 is reserved,remove all != 0 should remove all objects. 
   url = [NSURL URLWithString:[@"http://remote.bistolas.info:8888/query.php?query=delete from MAIN where ID!=0" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
   delReq = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
   [NSURLConnection sendSynchronousRequest:delReq returningResponse:nil error:nil]; 
   
   //Clear powerups table. 
   url = [NSURL URLWithString:[@"http://remote.bistolas.info:8888/query.php?query=delete from POWERUPS where ID!=0" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
   delReq = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
   [NSURLConnection sendSynchronousRequest:delReq returningResponse:nil error:nil]; 
   
   //Clear game data table
   url = [NSURL URLWithString:[@"http://remote.bistolas.info:8888/query.php?query=delete from GameData where ID!=0" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
   delReq = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
   [NSURLConnection sendSynchronousRequest:delReq returningResponse:nil error:nil]; 
}

- (void) dealloc {
   [playerName_ release];
   [players_ release];
   [powerups_ release];
   [startTarget_ release];
   [endTarget_ release]; 
   [super dealloc]; 
}

@end
